package com.qdsg.ysg.doctor.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.ViewCompat;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.service.WebSocketService;
import com.qdsg.ysg.doctor.util.DisplayUtil;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.client.RestClient;

import java.util.ArrayList;

import butterknife.ButterKnife;
import jz.joyoung.robot.util.NetworkUtil;

public abstract class BaseLoginActivity extends AppCompatActivity {
    public ImageView btn_back;
    public boolean flag = false;
    protected Activity mContext;
    private static ProgressDialog progressDialog;
    protected String TAG;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            //为了防止重复启动多个闪屏页面
            finish();
            return;
        }
        TAG = getClass().getSimpleName();
        mContext = this;
        doBeforeSetcontentView();
        setContentView(getLayoutResource());
        ButterKnife.bind(this);
        setStatusBar();
        initBack();
        initData();
        initViews();
        initState();
    }


    protected void setStatusBar() {
//        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary));
//        StatusBarUtil.setTranslucentForImageViewInFragment(BaseActivity.this, null);
    }

    public void initBack() {
        btn_back = findViewById(R.id.btn_back);
        if (btn_back != null) {
            btn_back.setOnClickListener(v -> finish());
        }
    }


    /**
     * 设置layout前配置
     */
    private void doBeforeSetcontentView() {
        // 把actvity放到application栈中管理
//        AppManager.getAppManager().addActivity(this);
        // 无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置竖屏
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivity(Class<?> cls) {
        startActivity(cls, null);
        overridePendingTransition(R.anim.activity_in_right, R.anim.activity_out_left);
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, int requestCode) {
        startActivityForResult(cls, null, requestCode);
        overridePendingTransition(R.anim.activity_in_right, R.anim.activity_out_left);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.activity_in_right, R.anim.activity_out_left);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.activity_in_right, R.anim.activity_out_left);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //我看可以重启服务，如果服务断了
        checkServiceRunning(mContext);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        AppManager.getAppManager().finishActivity(this);
    }

    /**
     * 清除editText的焦点
     *
     * @param v   焦点所在View
     * @param ids 输入框
     */
    public void clearViewFocus(View v, int... ids) {
        if (null != v && null != ids && ids.length > 0) {
            for (int id : ids) {
                if (v.getId() == id) {
                    v.clearFocus();
                    break;
                }
            }
        }
    }

    /**
     * 隐藏键盘
     *
     * @param v   焦点所在View
     * @param ids 输入框
     * @return true代表焦点在edit上
     */
    public boolean isFocusEditText(View v, int... ids) {
        if (v instanceof EditText) {
            EditText tmp_et = (EditText) v;
            for (int id : ids) {
                if (tmp_et.getId() == id) {
                    return true;
                }
            }
        }
        return false;
    }


    //是否触摸在指定view上面,对某个控件过滤
    public boolean isTouchView(View[] views, MotionEvent ev) {
        if (views == null || views.length == 0) {
            return false;
        }
        int[] location = new int[2];
        for (View view : views) {
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
//            return true;
//        }
//        lastClickTime = System.currentTimeMillis();
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isTouchView(filterViewByIds(), ev)) return super.dispatchTouchEvent(ev);
            if (hideSoftByEditViewIds() == null || hideSoftByEditViewIds().length == 0)
                return super.dispatchTouchEvent(ev);
            View v = getCurrentFocus();
            if (isFocusEditText(v, hideSoftByEditViewIds())) {
                //隐藏键盘
//                KeyBoardUtils.hideInputForce(this);
                clearViewFocus(v, hideSoftByEditViewIds());
            }
        }
        return super.dispatchTouchEvent(ev);

    }


    /**
     * 传入EditText的Id
     * 没有传入的EditText不做处理
     *
     * @return id 数组
     */
    public int[] hideSoftByEditViewIds() {
        return null;
    }

    /**
     * 传入要过滤的View
     * 过滤之后点击将不会有隐藏软键盘的操作
     *
     * @return id 数组
     */
    public View[] filterViewByIds() {
        return null;
    }

    protected abstract int getLayoutResource();

    protected abstract void initData();

    protected abstract void initViews();


    public void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = this.getWindow();
            //取消状态栏透明
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //添加Flag把状态栏设为可绘制模式
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(Color.parseColor("#ffffff"));
            //设置系统状态栏处于可见状态
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            //让view不根据系统窗口来调整自己的布局
            ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
            View mChildView = mContentView.getChildAt(0);
            if (mChildView != null) {
                ViewCompat.setFitsSystemWindows(mChildView, false);
                ViewCompat.requestApplyInsets(mChildView);
            }
        }
    }

    /**
     * 展示加载框
     *
     * @time 2020/4/21 11:16
     */
    public void showProgressDialog(Activity mActivity) {
        if (NetworkUtil.isNetworkAvailable(this)) {
            if (mActivity != null) {
                // 这个函数用来设置 Dialog 周围的颜色。系统默认的是半透明的灰色。值设为0则为完全透明。
                this.getWindow().setDimAmount(3);
                progressDialog = new ProgressDialog(BaseLoginActivity.this);
                //设置进度条风格，风格为圆形，旋转的
                progressDialog.setProgressStyle(
                        ProgressDialog.STYLE_SPINNER);
                //设置ProgressDialog 标题
//        progressDialog.setTitle("下载");
                //设置ProgressDialog 提示信息
                progressDialog.setMessage("加载中...");
                //设置ProgressDialog 标题图标
//        progressDialog.setIcon(android.R.drawable.btn_star);
                //设置ProgressDialog 的进度条是否不明确
                progressDialog.setIndeterminate(false);
                //设置ProgressDialog 是否可以按退回按键取消
                progressDialog.setCancelable(true);
                progressDialog.setProgressStyle(R.style.loading_dialog);
                // 让ProgressDialog显示
                progressDialog.show();
            }

        }

    }

    public void dismissProgressDialog() {
//        mHandler.postDelayed( sRunnable, 1000 );
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    /**
     * 打开设置权限页面
     */
    @SuppressLint("ObsoleteSdkInt")
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void startNotificationSetting(Context context) {
        try {
            Intent mIntent = new Intent();
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                mIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            } else {
                mIntent.setAction(Intent.ACTION_VIEW);
                mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                mIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
            }
            context.startActivity(mIntent);

        } catch (Exception ignored) {

        }
    }

    // 检查服务重新连接
    public void checkServiceRunning(Context context) {
        if (!UtilString.isEmpty(RestClient.getInstance().token) && !UtilString.isEmpty(BaseApplication.currentUserId)) {
            if (!isServiceRunning(mContext, "com.qdsg.ysg.doctor.service.WebSocketService")) {
                Log.e("基类服务死了---", "妈的");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(new Intent(mContext, WebSocketService.class));
                } else {
                    startService(new Intent(mContext, WebSocketService.class));
                }
            } else {
                Log.e("基类服务还在---", "哈哈哈");
            }
        } else {
            stopService(new Intent(mContext, WebSocketService.class));
        }
    }

    // 服务是否运行
    public boolean isServiceRunning(Context context, String serviceName) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        assert am != null;
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) am.getRunningServices(Integer.MAX_VALUE);

        for (ActivityManager.RunningServiceInfo info : runningService) {// 获取运行服务再启动
            if (info.service.getClassName().equals(serviceName)) {
                return true;
            }
        }
        return false;

    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        return DisplayUtil.getResources(this, resources, 1f);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(DisplayUtil.attachBaseContext(base, 1f));
    }
}